package mall.filter;

import com.google.gson.Gson;
import mall.model.Admin;
import mall.model.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 *
 * @author Yonni
 * @version 1.8.0_201
 * @date 2020-05-27 16:10
 *
 * */
//只拦截后台接口，前台不用拦截
@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //将*改为页面系统所在的域
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8085");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        //System.out.println(request.getMethod()); //OPTIONS POST

        String requestURI = request.getRequestURI();
        /*
        * 1. 需要拦截哪些，哪些不需要拦截
        * 2. 针对需要拦截的，判断有无session(主要防止用户在记得url的情况下，不登录访问)
        * 3. 如果没有则拦截
        * */
        //为提高性能，OPTIONS请求不需要拦截
        if (!request.getMethod().equals("OPTIONS")) {
            if (auth(requestURI)) {
                Admin admin = (Admin) request.getSession().getAttribute("admin");
                if (admin == null) {
                    response.getWriter().println(new Gson().toJson(Result.error("当前页面仅登录后可以访问")));
                    return;
                }
            }
        }
        chain.doFilter(request, response);

    }

    //当前请求URI是否需要权限
    private boolean auth(String requestURI) {
        //除了登录，均要权限
        if ("/api/admin/admin/login".equals(requestURI) ||
        "/api/admin/admin/logoutAdmin".equals(requestURI)) {
            return false;
        }
        return true;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
